# -*- coding: utf-8 -*-
#
# The Philatelist program is a fork of the OpenNumismat program
# Copyright (c) 2011 - 2024 Vitaly Ignatov (OpenNumismat) <opennumismat@gmail.com>
# Copyright (c) 2021 - 2024 Victor Nabatov (Philatelist) <nabatov.victor@gmail.com>

from PySide6.QtSql import QSqlQuery
from PySide6.QtWidgets import QMessageBox

from Philatelist.Tools.Gui import ProgressDialog
from Philatelist import version


class MergeDatabases():

    def __init__(self, collection):
        self.collection = collection

    def merge(self, file_name):
        fields_query = QSqlQuery("PRAGMA table_info(stamps)", self.collection.db)
        fields_query.exec_()
        fields = []
        while fields_query.next():
            fields.append(fields_query.record().value(1))

        fields.remove('id')
        sql_fields = ','.join(fields)
        query = QSqlQuery("SELECT MAX(sort_id) FROM stamps", self.collection.db)
        query.first()
        sort_id = query.record().value(0)

        query = QSqlQuery(self.collection.db)
        query.prepare("ATTACH ? AS src")
        query.addBindValue(file_name)
        result = query.exec_()
        if not result:
            QMessageBox.critical(
                self.collection.parent(),
                self.collection.tr("Synchronizing"),
                self.collection.tr("Can't open collection:\n%s") % query.lastError().text()
            )
            return

        query = QSqlQuery("SELECT COUNT(*) FROM src.stamps", self.collection.db)
        query.first()
        count = query.record().value(0)
        progressDlg = ProgressDialog(
            self.collection.tr("Merging"),
            self.collection.tr("Cancel"),
            count,
            self.collection.parent()
        )
        inserted_count = 0
        self.collection.db.transaction()
        sql = "SELECT * FROM src.stamps"
        src_query = QSqlQuery(sql, self.collection.db)
        src_query.exec_()
        while src_query.next():
            sql = "INSERT INTO stamps (%s) VALUES (%s)" % (sql_fields, ','.join(['?'] * len(fields)))
            ins_query = QSqlQuery(sql, self.collection.db)
            for field in fields:
                if field == 'image':
                    old_img_id = src_query.record().value(field)
                    if old_img_id:
                        sql = "INSERT INTO images (image) SELECT image FROM src.images WHERE id=?"
                        img_query = QSqlQuery(sql, self.collection.db)
                        img_query.addBindValue(old_img_id)
                        img_query.exec_()

                        img_id = img_query.lastInsertId()
                    else:
                        img_id = None

                    ins_query.addBindValue(img_id)

                elif field == 'sort_id':
                    ins_query.addBindValue(sort_id + 1)
                else:
                    ins_query.addBindValue(src_query.record().value(field))

            ins_query.exec_()
            self.collection.db.commit()
            inserted_count += 1

            progressDlg.step()
            if progressDlg.wasCanceled():
                break

        self.collection.model().submitAll()
        progressDlg.reset()

        query = QSqlQuery("DETACH src", self.collection.db)
        query.exec_()

        if inserted_count:
            text = self.collection.tr("Inserted %d stamp(s).\nThe application needs to be restarted.") % (inserted_count)
        else:
            text = self.collection.tr("Collections is not merged")

        QMessageBox.information(
            self.collection.parent(),
            self.collection.tr("Merging"),
            text
        )
        # TODO: refresh
        self.collection.parent().restart()
